//
//  TFPlaceholderTextView.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/7/14.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPlaceholderTextView.h"

@interface TFPlaceholderTextView ()

@property (nonatomic, strong, readwrite) UILabel *placeholderLabel;

@end

@implementation TFPlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self addSubview:self.placeholderLabel];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(p_textDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat x, y, width, height;
    x = self.placeholderInsets.left;
    y = self.placeholderInsets.top;
    width = CGRectGetWidth(self.frame) - 2 * x;
    height = 40.f;
    
    self.placeholderLabel.frame = CGRectMake(x, y, width, height);
}

- (void)p_textDidChange:(NSNotification *)noti {
    if (noti.object==self) {
        _placeholderLabel.hidden = self.text.length;
    }
}


- (UILabel *)placeholderLabel {
    if (!_placeholderLabel) {
        _placeholderLabel = [[UILabel alloc] init];
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        _placeholderLabel.font = [UIFont systemFontOfSize:20];
        _placeholderLabel.numberOfLines = 0;
    }
    return _placeholderLabel;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
